﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;
using nRoute.Navigation.Containers;
using nRoute.SiteMaps;

namespace nRoute.Samples.Netflix.Behaviors
{
    public class TextBoxWatermarkBehavior
        : Behavior<UIElement>
    {
        public static readonly DependencyProperty TextBoxProperty =
           DependencyProperty.Register("TextBox", typeof(TextBox), typeof(TextBoxWatermarkBehavior),
           new PropertyMetadata(null));

        public TextBox TextBox
        {
            get { return (TextBox)(GetValue(TextBoxProperty)); }
            set { SetValue(TextBoxProperty, value); }
        }

#region Overrides

        protected override void OnAttached()
        {
            base.OnAttached();

            if (this.TextBox == null) return;
            this.TextBox.GotFocus += new RoutedEventHandler(TextBox_GotFocus);
            this.TextBox.LostFocus += new RoutedEventHandler(TextBox_LostFocus);
            this.TextBox.TextChanged += new TextChangedEventHandler(TextBox_TextChanged);
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();

            if (this.TextBox == null) return;
            this.TextBox.GotFocus -= new RoutedEventHandler(TextBox_GotFocus);
            this.TextBox.LostFocus -= new RoutedEventHandler(TextBox_LostFocus);
            this.TextBox.TextChanged -= new TextChangedEventHandler(TextBox_TextChanged);
            this.TextBox = null;
        }

#endregion

#region Handler

        private void TextBox_GotFocus(object sender, RoutedEventArgs e)
        {
            this.AssociatedObject.Visibility = Visibility.Collapsed;
        }

        private void TextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            this.AssociatedObject.Visibility = string.IsNullOrEmpty(this.TextBox.Text) ?
                Visibility.Visible : Visibility.Collapsed;
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            this.AssociatedObject.Visibility = (string.IsNullOrEmpty(this.TextBox.Text) && !this.TextBox.IsFocused) ?
                Visibility.Visible : Visibility.Collapsed;
        }

#endregion
    
    }
}
